package cn.com.anypay.manager.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import jakarta.annotation.PostConstruct;
import java.util.Arrays;

@Configuration
public class CorsConfig {

    private static final Logger logger = LoggerFactory.getLogger(CorsConfig.class);

    @Value("${cors.allowed-origins:http://localhost:3000}")
    private String[] allowedOrigins;

    @PostConstruct
    public void init() {
        logger.info("CORS配置初始化 - 原始配置的跨域源: {}", Arrays.toString(allowedOrigins));

        // 强制确保包含生产环境域名
        String[] requiredOrigins = {"https://www.suantai.com", "http://localhost:3000"};
        boolean needsUpdate = false;

        for (String required : requiredOrigins) {
            boolean found = false;
            for (String existing : allowedOrigins) {
                if (required.equals(existing)) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                needsUpdate = true;
                break;
            }
        }

        if (needsUpdate) {
            logger.warn("CORS配置不完整，强制添加必需的跨域源");
            allowedOrigins = requiredOrigins;
        }

        logger.info("CORS配置最终确定 - 允许的跨域源: {}", Arrays.toString(allowedOrigins));
    }

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        logger.info("创建CORS配置器 - 允许的跨域源: {}", Arrays.toString(allowedOrigins));
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                logger.info("添加CORS映射 - 允许的跨域源: {}", Arrays.toString(allowedOrigins));
                registry.addMapping("/**")
                        .allowedOrigins(allowedOrigins)
                        .allowedMethods("*")
                        .allowedHeaders("*")
                        .exposedHeaders("Authorization")
                        .allowCredentials(true);
                logger.info("CORS映射配置完成");
            }
        };
    }
}
